package cn.promonkey.api.student.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.promonkey.core.dto.UserDto;
import cn.promonkey.core.response.ResultMsg;
import cn.promonkey.core.toolkit.QueryGenerator;
import cn.promonkey.core.toolkit.UserInfoUtils;
import cn.promonkey.core.utils.MD5Utils;
import cn.promonkey.api.student.entity.Student;
import cn.promonkey.api.student.service.StudentService;
import cn.promonkey.api.user.entity.User;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;

/** @author <no value> */
@Slf4j
@RestController
@RequestMapping("/student/")
public class StudentController {
  final StudentService studentService;

  public StudentController(StudentService studentService) {
    this.studentService = studentService;
  }

  @RequestMapping("getPage")
  public String getPage(
      Student student,
      @RequestParam(name = "page", defaultValue = "1") Integer page,
      @RequestParam(name = "size", defaultValue = "10") Integer size,
      HttpServletRequest request) {
    QueryWrapper<Student> queryWrapper = QueryGenerator.initQueryWrapper(student, request.getParameterMap());
    Page<Student> pageable = new Page<>(page, size);
    IPage<Student> pageList = studentService.page(pageable, queryWrapper);
    return ResultMsg.success(pageList);
  }

  @RequestMapping(value = "save", method = RequestMethod.POST)
  public String save(@RequestBody Student student) {
    return ResultMsg.success(studentService.save(student));
  }

  @RequestMapping(value = "edit", method = RequestMethod.POST)
  public String edit(@RequestBody Student student) {
    return ResultMsg.success(studentService.updateById(student));
  }

  @RequestMapping(value = "get")
  public String get(@RequestParam(name = "id") Long id) {
    return ResultMsg.success(studentService.getById(id));
  }

  @RequestMapping(value = "delete", method = RequestMethod.POST)
  public String delete(@RequestBody Long id) {
    return ResultMsg.success(studentService.removeById(id));
  }
  
  @RequestMapping("upload")
  public String upload(MultipartFile file,HttpServletRequest httpServletRequest) throws SocketException, IOException {
		
	UserDto userDto = UserInfoUtils.getUserInfo();
	List<Student> userList = new ArrayList<>();
	List<Student> updList = new ArrayList<>();

	Workbook workbook = new XSSFWorkbook(file.getInputStream());
	// 如果excel的后缀是xls,说明是03版，需要用如下方法
	// Workbook workbook = new HSSFWorkbook(is);
	//读取工作簿的第一张表格
	Sheet sheet = workbook.getSheetAt(0);
	  
	for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) {
		Row row = sheet.getRow(i);
		Student temp = new Student();
		temp.setStudentNum(getCellValue(row.getCell(0)));
		temp.setStudentName(getCellValue(row.getCell(1)));
		temp.setMajor(getCellValue(row.getCell(2)));
		temp.setTasGrade(getCellValue(row.getCell(3)));
		temp.setTasClass(getCellValue(row.getCell(4)));
		temp.setTelephone(getCellValue(row.getCell(5)));
	  	temp.setBusinessId(userDto.getBusinessId());
	  	QueryWrapper<Student> userWrapper = new QueryWrapper<>();
	  	userWrapper.eq("student_num", temp.getStudentNum());
	  	List<Student> list = studentService.list(userWrapper);
	  	if(list.size()>0) {
	  		Student t = list.get(0);
	  		t.setStudentName(getCellValue(row.getCell(1)));
			t.setMajor(getCellValue(row.getCell(2)));
			t.setTasGrade(getCellValue(row.getCell(3)));
			t.setTasClass(getCellValue(row.getCell(4)));
			t.setTelephone(getCellValue(row.getCell(5)));
	  		updList.add(t);
  		
	  	}else {
	  		userList.add(temp);
	  	}
	  }
			
	  if(userList.size()>0) {
		  studentService.saveBatch(userList);
	  }
	  if(updList.size()>0) {
		  studentService.updateBatchById(updList);
	  }
  
	  return ResultMsg.success();
  }

	private String getCellValue(Cell cell) {
		if (cell == null) {
			return "";
		}
		if ("NUMERIC".equals(cell.getCellType().name())) {
			return new BigDecimal(cell.getNumericCellValue()).toString();
		} else if ("STRING".equals(cell.getCellType().name()))
			return StringUtils.trimToEmpty(cell.getStringCellValue());
		else if ("FORMULA".equals(cell.getCellType().name())) {
			return StringUtils.trimToEmpty(cell.getCellFormula());
		} else if ("BLANK".equals(cell.getCellType().name())) {
			return "";
		} else if ("BOOLEAN".equals(cell.getCellType().name())) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if ("ERROR".equals(cell.getCellType().name())) {
			return "ERROR";
		} else {
			return cell.toString().trim();
		}
	}
}
